package com.wxzz.elearing.file.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.internal.ObsProperties;
import com.obs.services.internal.ServiceException;
import com.obs.services.model.PutObjectResult;
import com.wxzz.elearing.file.util.ImageUtil;
import com.wxzz.elearing.file.util.ObsFileUtil;
import com.wxzz.elearning.common.dto.FeignDrawImageDto;
import com.wxzz.elearning.common.utils.QRCodeUtil;
import com.wxzz.elearning.common.vo.ReturnVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.ServerException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class ObsService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif", "image/png");
    private static final Logger LOGGER = LoggerFactory.getLogger(ObsService.class);


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public ReturnVO upload(MultipartFile file) {
        String contype = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        String sub = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        //todo 暂时所有文件都能传
//        if ("video/avi".contains(contype)) {
//            LOGGER.info("文件类型不支持" + originalFilename);
//            throw new ServiceException("文件类型不支持");
//        }
//        if (!CONTENT_TYPES.contains(contype)) {
//            LOGGER.info("文件类型出错" + originalFilename);
//            return null;
//        }
//        try {
//            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//            if (bufferedImage == null) {
//                LOGGER.info("文件内容不合法" + originalFilename);
//                return null;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.err.println("获取文件流失败");
//        }
        //上传图片
        InputStream in = null;
        ObsClient obsClient = null;
        try {
            boolean video = ObsFileUtil.isVideo(file);

            int videoDuration = 0;
            log.info("是否为视频对象[{}]", video);
            if (video) {
                log.info("文件名[{}],文件对象[{}]", file.getOriginalFilename(), file.toString());
                videoDuration = ObsFileUtil.getVideoDuration(file);
                if(!"video/mp4".contains(contype)){
                    throw new ServiceException("视频只支持mp4格式");
                }
            }
            //获取图片名称，作为上传文件名参数
            String objectKey = file.getOriginalFilename()+"|"+UUID.randomUUID().toString();
            //获取流对象
            in = file.getInputStream();
            // 创建ObsClient实例
            obsClient = new ObsClient("0LKQHLIEKCJXIFHVTDYQ", "1td0PzShBjFTEBD94yA9U3XCey2hbkgWhcoHs50O", "obs.cn-south-1.myhuaweicloud.com");
            // 使用访问OBS
            PutObjectResult putObjectResult = obsClient.putObject("wxzz", objectKey, in);
            //将图片信息封装起来，方便前端回显调用
            String url = putObjectResult.getObjectUrl();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", objectKey);
            jsonObject.put("url", url);
            jsonObject.put("videoTime", videoDuration);
            return new ReturnVO("图片上传成功", jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("输出流关闭失败！");
            }
            try {
                if (obsClient != null) {
                    // 关闭obsClient
                    obsClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("obs客户端流对象关闭失败！");
            }

        }
        return null;
    }


    /**
     * 生成证书
     *
     * @return
     */
    public String upload(InputStream inputStream) {
        //todo 暂时所有文件都能传
//        if (!CONTENT_TYPES.contains(contype)) {
//            LOGGER.info("文件类型出错" + originalFilename);
//            return null;
//        }
//        try {
//            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//            if (bufferedImage == null) {
//                LOGGER.info("文件内容不合法" + originalFilename);
//                return null;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.err.println("获取文件流失败");
//        }
        //上传图片
        InputStream in = null;
        ObsClient obsClient = null;
        try {
            //获取图片名称，作为上传文件名参数
            String objectKey = UUID.randomUUID().toString() + ".jpg";
            // 创建ObsClient实例
            obsClient = new ObsClient("0LKQHLIEKCJXIFHVTDYQ", "1td0PzShBjFTEBD94yA9U3XCey2hbkgWhcoHs50O", "obs.cn-south-1.myhuaweicloud.com");
            // 使用访问OBS
            PutObjectResult putObjectResult = obsClient.putObject("wxzz", objectKey, inputStream);
            //将图片信息封装起来，方便前端回显调用
            String url = putObjectResult.getObjectUrl();
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("输出流关闭失败！");
            }
            try {
                if (obsClient != null) {
                    // 关闭obsClient
                    obsClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("obs客户端流对象关闭失败！");
            }

        }
        return null;
    }

    /**
     * 获得证书路径(远程调用)
     *
     * @param feignDrawImageDto
     * @return
     */
    @SneakyThrows
    public String getCredentialUrl(FeignDrawImageDto feignDrawImageDto) {
        return ImageUtil.drawImage(feignDrawImageDto.getBackgroundImageUrl(),
                null,
                feignDrawImageDto.getCredentialCode(),
                feignDrawImageDto.getItemText(),
                feignDrawImageDto.getNameText(),
                feignDrawImageDto.getStarText(),
                feignDrawImageDto.getCredentialTextOne(),
                feignDrawImageDto.getCredentialTextTwo(),
                feignDrawImageDto.getCredentialTextThree(),
                "",
                feignDrawImageDto.getCreateTime(),
                feignDrawImageDto.getEndTime(),
                feignDrawImageDto.getEnterpriseName(),
                "",
                feignDrawImageDto.getCommonUrlTwo());
    }

    public static void main(String[] args) {
        ObsService obsService = new ObsService();
        obsService.makeActivityImage(12312L);
    }

    /**
     * 生成活动二维码
     *
     * @return
     */
    public String makeActivityImage(Long activityId) {
        //生成二维码
        //上传图片
        InputStream in = null;
        ObsClient obsClient = null;
        try {
            //获取流对象
            in = QRCodeUtil.getImageInputStream("http://links.mp.wxzzapp.com/qr/signIn?actvityId=" + activityId, null, true);
            // 创建ObsClient实例
            obsClient = new ObsClient("0LKQHLIEKCJXIFHVTDYQ", "1td0PzShBjFTEBD94yA9U3XCey2hbkgWhcoHs50O", "obs.cn-south-1.myhuaweicloud.com");
            // 使用访问OBS
            PutObjectResult putObjectResult = obsClient.putObject("wxzz", activityId + ".jpg", in);
            //将图片信息封装起来，方便前端回显调用
            String imageUrl = putObjectResult.getObjectUrl();
            JSONObject jsonObject = new JSONObject();
            return imageUrl;
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("输出流关闭失败！");
            }
            try {
                if (obsClient != null) {
                    // 关闭obsClient
                    obsClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("obs客户端流对象关闭失败！");
            }

        }
        return null;
    }

    /**
     * 生成支付二维码
     * <p>
     * code_url 支付路径
     *
     * @param
     * @return
     * @throws Exception
     */
    public ReturnVO<String> makePayImage(Map<String, String> map) {
        //生成二维码
        //上传图片
        InputStream in = null;
        ObsClient obsClient = null;
        try {
            //获取流对象
            in = QRCodeUtil.getImageInputStream(map.get("code_url"), null, true);
            // 创建ObsClient实例
            obsClient = new ObsClient("0LKQHLIEKCJXIFHVTDYQ", "1td0PzShBjFTEBD94yA9U3XCey2hbkgWhcoHs50O", "obs.cn-south-1.myhuaweicloud.com");
            // 使用访问OBS
            PutObjectResult putObjectResult = obsClient.putObject("wxzz", map.get("code_url") + ".jpg", in);
            //将图片信息封装起来，方便前端回显调用
            String imageUrl = putObjectResult.getObjectUrl();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", map.get("code_url"));
            jsonObject.put("url", imageUrl);
            return new ReturnVO("图片上传成功", jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("上传图片失败!");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("输出流关闭失败！");
            }
            try {
                if (obsClient != null) {
                    // 关闭obsClient
                    obsClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("obs客户端流对象关闭失败！");
            }

        }
        return null;
    }
}
